<template>
  <div class="order_page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <el-form-item label="工单名称" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入工单名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="是否接收" prop="type">
              <el-select v-model="queryParams.type" placeholder="是否认领" clearable style="width: 240px">
                <el-option v-for="dict in event_server_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="工单状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="工单状态" clearable style="width: 240px">
                <el-option v-for="dict in event_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header v-if="false">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple"> 删除 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="dataList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工单名称" align="center" prop="title"></el-table-column>
        <el-table-column label="工单状态" align="center" prop="dictValue">
          <template #default="{row}">
            <dict-tag :options="event_order_status" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="发起人" align="center" prop="reportName" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template #default="{row}">
            <el-button v-has-permi="['event:workOrder:detail']" link type="primary" icon="Pointer" @click="lookInfo(row)">查看</el-button>
            <el-button v-has-permi="['event:workOrder:accept']" link type="primary" icon="EditPen" @click="receiveFn(row)" v-if="row.status==1">接收</el-button>
            <el-button v-has-permi="['event:workOrder:allot']" link type="primary" icon="Promotion" @click="allocateUser(row)" v-if="row.status==2">分配</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 查看工单信息 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dataFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单名称">
          <el-input v-model="form.title" :disabled="true" />
        </el-form-item>
        <el-form-item label="工单描述">
          <el-input v-model="form.detail" :disabled="true" />
        </el-form-item>
        <el-form-item label="工单状态">
          <dict-tag :options="event_order_status" :value="form.status" />
        </el-form-item>
        <el-form-item label="发起人">
          <el-input v-model="form.reportName" :disabled="true" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配工程师 -->
    <el-dialog :title="allocationDialog.title" v-model="allocationDialog.visible" :align-center="true" width="800px">
      <div class="user_box">
        <div class="left_tree">
          <el-tree class="mt-2" ref="deptTreeRef" node-key="id" :data="deptOptions" :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false" highlight-current default-expand-all @node-click="handleNodeClick" />
        </div>
        <div class="right_user">
          <el-table :data="userData" border @selection-change="selectUser" height="60vh">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="用户id" align="center" prop="userId" /> -->
            <el-table-column label="用户名称" align="center" prop="nickName"></el-table-column>
            <el-table-column label="手机号码" align="center" prop="phonenumber" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情 -->
     <!--   -->
    <el-drawer v-model="detailFlag" :title="'详情'" direction="rtl" size="40%" :close-on-click-modal="true">
      <div class="df jc-c ai-c">
        <el-steps style="width: 100%;margin: 0 auto;display: flex;justify-content: center;align-items: center;" :space="200" 
        :active="Number(form.status)" finish-status="success">
          <!-- 1.发布 2.待分配 3.工程师待接收 4.处理中 5.结束 -->
          <el-step title="发布" />
          <el-step title="待分配" />
          <el-step title="工程师待接收" />
          <el-step title="处理中" />
          <el-step title="结束" />
        </el-steps>
      </div>
      <div style="margin-top: 30px;">
        <el-descriptions :title="'标题：'+form?.title" v-if="false">
          <el-descriptions-item label="工单详情：">{{form?.detail}}</el-descriptions-item>
          <el-descriptions-item label="工单创建时间：">{{form?.createTime}}</el-descriptions-item>
          <el-descriptions-item label="工单提交时间：">{{form?.submitTime}}</el-descriptions-item>
          <el-descriptions-item label="服务台人员名称：">{{form?.serviceName}}</el-descriptions-item>
          <el-descriptions-item label="服务台人员接单时间：">{{form?.serviceTime}}</el-descriptions-item>
          <el-descriptions-item label="工程师名称：">{{form?.engineName}}</el-descriptions-item>
          <el-descriptions-item label="工程师接单时间：">{{form?.engineReceiveTime}}</el-descriptions-item>
          <el-descriptions-item label="工程师解决方案：">{{form?.engineSoluion}}</el-descriptions-item>
          <el-descriptions-item label="工程师完成时间：">{{form?.engineFinshTime}}</el-descriptions-item>
          <el-descriptions-item label="工单状态：" class="df">
            <div class="df"><dict-tag :options="event_order_status" :value="form?.status" /></div
          ></el-descriptions-item>
          <el-descriptions-item label="申报人名称：">{{form?.reportName}}</el-descriptions-item>
          <el-descriptions-item label="用户图片：">
              <div v-if="form?.userPath&&form.userPath.length > 0">
                <div v-for="(url,index) in form.userPath" :key="index">
                  <el-image style="width: 100px; height: 100px" 
                  :src="url" :zoom-rate="1.2" 
                  :max-scale="7" :min-scale="0.2" 
                  :preview-src-list="form.userPath" 
                  :initial-index="4" fit="cover" />
                </div>
              </div>
              <span v-else>-</span>
          </el-descriptions-item>
          
          <el-descriptions-item label="工程师图片：">
            <div v-if="form?.enginePath&&form.enginePath.length > 0">
              <div v-for="(url, index) in form.enginePath" :key="index">
                <el-image style="width: 100px; height: 100px" :src="url" 
                :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" 
                :preview-src-list="[form?.enginePath]" :initial-index="4" fit="cover" />
              </div>
            </div>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div style="margin-top: 30px;">
        <div class="card_cell">
          <div class="card_title">
            <span>工单名称:{{ form?.title }}</span>
          </div>
          <div class="card_line">
            <div class="card_label">工单详情：</div>
            <div class="card_value">{{form?.detail}} </div>
          </div>
          <div class="card_line">
            <div class="card_label">工单状态：</div>
            <div class="card_value">
              <dict-tag :options="event_order_status" :value="form?.status" />
            </div>
          </div>
          <div class="card_line">
            <div class="card_label">工单图片：</div>
            <div class="card_value">
              <div v-if="form?.userPath&&form.userPath.length > 0" class="img_list">
                <el-image class="image_box"  v-for="(url,index) in form.userPath" :key="index"
                :src="url" :zoom-rate="1.2" 
                :max-scale="7" :min-scale="0.2" 
                :preview-src-list="form.userPath" 
                :initial-index="4" fit="fill"/>
              </div>
              <div class="image_box" v-else>
                <span>暂无图片</span>
              </div>
            </div>
          </div>
          <div class="card_line">
            <div class="card_label">发起人：</div>
            <div class="card_value">{{form?.reportName}} </div>
          </div>
          <div class="card_line">
            <div class="card_label">创建时间：</div>
            <div class="card_value">{{form?.createTime}} </div>
          </div>
          <div class="card_line">
            <div class="card_label">服务台人员：</div>
            <div class="card_value">{{form?.serviceName}} </div>
          </div>
        </div>
        <div class="card_cell">
          <div class="card_title">
            <span>工程师：{{form?.engineName}}</span>
          </div>
          <div class="card_line">
            <div class="card_label">解决方案：</div>
            <div class="card_value">{{form?.engineSoluion}}</div>
          </div>
          <div class="card_line">
            <div class="card_label">解决时间：</div>
            <div class="card_value">{{form?.engineFinshTime}}</div>
          </div>
          <div class="card_line">
            <div class="card_label">解决图片：</div>
            <div class="card_value">
              <div v-if="form?.enginePath&&form.enginePath.length > 0" class="img_list">
                <el-image class="image_box"  v-for="(url,index) in form.enginePath" :key="index"
                :src="url" :zoom-rate="1.2" 
                :max-scale="7" :min-scale="0.2" 
                :preview-src-list="form.enginePath" 
                :initial-index="4" fit="fill"/>
              </div>
              <div class="image_box" v-else>
                <span>暂无图片</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import api from '@/api/system/user';
import { getWorkOrderListAPI, getWorkOrderInfoAPI, getUserListAPI,
    allocationOrderAPI, receiveAPI
 } from "@/api/event/workOrder/index"
import { DeptVO } from '@/api/system/dept/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { event_order_status } = toRefs<any>(proxy?.useDict("event_order_status"));
const { event_server_status } = toRefs<any>(proxy?.useDict("event_server_status"));

const dataList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);


const queryFormRef = ref<ElFormInstance>();


const deptOptions = ref<DeptVO[]>([]);
const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: any = {
    id: undefined,
    status: "0",
    title: "",
    reportName: "",
    detail: "",
    filePath: "", //用户图片
    engineImages: ""
}

const data = reactive<PageData<any, any>>({
    form: { ...initFormData },
    queryParams: <any>{
        pageNum: 1,
        pageSize: 10,
        type: "", // 1表示待接收 2表示已接收
        title: "",
        status: ""
    },
    rules: {}
});

const { queryParams, form, rules } = toRefs(data);

const allocationDialog = reactive({
    visible: false,
    title: "分配工单"
})
const allocationFormData = {
    id: "",
    engineIds:<any[]> []
}
const allocationData = reactive({
    allocationForm: {...allocationFormData},
    allocationParams:{
        deptId: ""
    }
})

let { allocationForm, allocationParams } = toRefs(allocationData)
// 用户列表
let userData = ref([])

async function getList() {
    loading.value = true;
    const res = await getWorkOrderListAPI(queryParams.value)
    dataList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

function resetQuery() {
    queryFormRef.value?.resetFields();
    queryParams.value.pageNum = 1;
    handleQuery();
}

async function submitForm() {
    allocationDialog.visible = false
    console.log(allocationForm.value)
    const res = await allocationOrderAPI(allocationForm.value)
    if(res.code == 200) {
        ElMessage.success("分配成功")
        getList()
    }
}

function cancel() {
    allocationDialog.visible = false
}

// 分配用户
function allocateUser(row:any) {
    allocationForm.value.id = row.id
    getUserList()
    allocationDialog.visible = true
}

const detailFlag = ref<boolean>(false)
async function lookInfo(row:any) {
    const res = await getWorkOrderInfoAPI(row.id)
    console.log("获取到的详细信息", res)

    form.value = res.data
    detailFlag.value = true
    // dialog.visible = true
}

function receiveFn(row:any) {
    ElMessageBox.confirm(
        `是否接收该工单，接收之后方可进行分配！`,
        '提示',
        {
        confirmButtonText: '接收',
        cancelButtonText: '取消',
        type: 'warning',
        }
    )
        .then(async () => {
            const res = await receiveAPI({
                id: row.id,
                type: 1
            })
            if(res.code == 200) {
                ElMessage.success("接收成功？")
                getList()
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '操作取消',
            })
        })

}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

/** 节点单击工单 */
const handleNodeClick = (data: DeptVO) => {
    allocationParams.value.deptId = String(data.id);
    getUserList();
};

function selectUser(selection:any[]) {
    allocationForm.value.engineIds = selection.map(item => item.userId);
}

async function getUserList() {
    const res = await getUserListAPI(allocationParams.value.deptId)
    console.log("获取到的用户列表", res)
    userData.value = res.data
}

onMounted(() => {
    getTreeSelect()
    getList()
})
</script>

<style scoped lang="scss">
.user_box {
    width: 100%;
    display: flex;
    height: 60vh;
    .left_tree {
        width: 200px;
        height: 100%;
    }
    .right_user {
        flex: 1;
        height: 100%;
    }
}

.card_cell {
  width: 100%;
  .card_title {
    font-size: 24px;
    font-weight: bold;
  }
  .card_line {
    display: flex;
    line-height: 24px;
    margin: 12px 0;
    .img_list {
      display: flex;
      align-items: center;
    }
    .image_box {
        width: 100px;
        height: 100px;
        margin-right: 16px;
        background-color: #f8f8f8;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
      }
  }
}
</style>
